<template>
  <view class="wrap">
    <view>
      {{ answer }}
    </view>
    <view class="bottom-bar">
      <view class="left" @tap.stop="onPlayIconClick">
        <image src="@/static/imgs/play_icon.png" mode="widthFix"></image>
        <text>英语朗读</text>
      </view>
      <view class="right">
        <button open-type="share">
          <image src="@/static/imgs/share_icon.png" mode="widthFix"></image>
        </button>
        <image
          src="@/static/imgs/copy_icon.png"
          mode="widthFix"
          @tap.stop="onCopyIconClick"
        ></image>
        <image
          src="@/static/imgs/zan_icon.png"
          mode="widthFix"
          @tap.stop="onZanIconClick"
        ></image>
        <image
          src="@/static/imgs/cai_icon.png"
          mode="widthFix"
          @tap.stop="onCaiIconClick"
        ></image>
      </view>
    </view>
    <view
      class="bottom-bar"
      style="margin-top: 20rpx"
      @tap.stop="jumpBreakAnswerPage"
    >
      <view class="left">
        <image src="@/static/imgs/en_icon.png" mode="widthFix"></image>
        <text>分段陪练</text>
      </view>
    </view>
  </view>
  <bottomEnter />
</template>

<script lang="ts" setup>
import { ref } from 'vue'
import { tnNavPage } from '@tuniao/tnui-vue3-uniapp/utils'
import { bottomEnter } from '@/components/bottom-enter'
import { useWebsocket } from '@/hooks'
import { onLoad, onHide, onUnload } from '@dcloudio/uni-app'
import { Base64 } from 'js-base64'
import storageApi from '@/utils/storage'
var plugin = requirePlugin('WechatSI')
let manager = plugin.getRecordRecognitionManager()

const innerAudioContext = uni.createInnerAudioContext()
const { handleClickVideo, webSocketSendMp3, handleCloseVideo } = useWebsocket()

const answer = ref('')
const audioSrc = ref('')

onLoad((options) => {
  if (options.answerZh) {
    onTranslate(options.answerZh)
  }
})

onHide(() => {
  handleCloseVideo()
})

onUnload(() => {
  handleCloseVideo()
})

const jumpBreakAnswerPage = () => {
  let encoded = Base64.btoa(unescape(encodeURIComponent(answer.value)))
  tnNavPage(`/home-page/agent/break-answer?answerEn=${encoded}&source=1`)
}

//中文翻译成英文
const onTranslate = (answerZh) => {
  plugin.translate({
    lfrom: 'zh_CN',
    lto: 'en_US',
    content: answerZh,
    success: function (res) {
      if (res.retcode == 0) {
        answer.value = res.result
        // outputText(answer.value)
      } else {
        console.warn('翻译失败', res)
        uni.showToast({
          title: '翻译失败，原因：翻译内容超长',
          duration: 2000,
          icon: 'none',
        })
      }
    },
    fail: function (res) {
      console.log('网络失败', res)
    },
  })
}

//英文转语音
const textToSpeech = () => {
  return new Promise((resolve, reject) => {
    plugin.textToSpeech({
      lang: 'en_US',
      tts: true,
      content: answer.value,
      success: function (res) {
        console.log('succ tts', res.filename)
        audioSrc.value = res.filename
        resolve()
      },
      fail: function (res) {
        console.log('fail tts', res)
      },
    })
  })
}

const stopAudio = () => {
  innerAudioContext.stop()
}

const onPlayIconClick = () => {
  // Chinese中文 | English英文
  webSocketSendMp3(answer.value, 'English').then((res) => {
    let newArr = []
    res.map((item, index) => {
      const arrayBuffer = wx.base64ToArrayBuffer(item)
      const newBuffer = new Uint8Array(arrayBuffer)
      newArr.push(...newBuffer)
    })
    let uint8Array = new Uint8Array(newArr)
    const newUrl = wx.createBufferURL(uint8Array.buffer)
    handleClickVideo(newUrl)
  })
}

// const onPlayIconClick = async () => {
//   await textToSpeech()

//   innerAudioContext.src = audioSrc.value
//   innerAudioContext.play()
//   innerAudioContext.onPlay(() => {
//     console.log('开始播放')
//     if (!storageApi.get('isFirstEn')) {
//       uni.showToast({
//         title: '朗读中，请注意确保手机不是静音状态',
//         duration: 1000,
//         icon: 'none',
//       })
//     }
//     storageApi.set('isFirstEn', true)
//   })
//   innerAudioContext.onError((err) => {
//     console.log(err.errMsg)
//   })
//   innerAudioContext.onEnded(() => {
//     innerAudioContext = null
//   })
// }

const onCopyIconClick = () => {
  uni.setClipboardData({
    data: answer.value,
    success: function () {},
  })
}

const onZanIconClick = () => {
  uni.showToast({
    title: '已赞',
    duration: 2000,
  })
}

const onCaiIconClick = () => {
  uni.showToast({
    title: '已踩',
    duration: 2000,
  })
}
</script>

<style lang="scss" scoped>
.problem-title {
  margin: 40rpx auto;
  text-align: center;
  font-size: 26rpx;
  font-weight: bold;
  font-family: 'tuniao-xiaowei';
}
.wrap {
  width: 90%;
  margin: 0 5%;
  padding: 40rpx 20rpx;
  border-radius: 20rpx;
  background-color: #fff;
  font-size: 24rpx;
  font-family: 'tuniao-xiaowei';
}
image {
  width: 50rpx;
}
.bottom-bar {
  margin-top: 40rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
  .left {
    image {
      vertical-align: middle;
      margin-right: 14rpx;
    }
  }
  .left {
    text {
      vertical-align: middle;
      color: #876fd1;
    }
  }
  .right {
    display: flex;
    button {
      background-color: #fff;
      width: 44rpx;
      margin: 0;
      padding: 0;
      position: relative;
      margin-right: 12rpx;
      image {
        position: absolute;
        top: 0;
        left: 0;
      }
    }
    image {
      margin-right: 18rpx;
    }
  }
}
</style>
